package com.zhangmeng.tools.editors.ace;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

public class AceHelper {

    private static final String ace_js = "/static/editors/ace-builds/src-min/ace.js";
    private static final String ext_language_tools_js = "/static/editors/ace-builds/src-min/ext-language_tools.js";

    public static String getHtml(AceMode aceMode, AceTheme aceTheme) {
        String theme_js = "/static/editors/ace-builds/src-min/" + aceTheme.getName();

        try (
                InputStream aceJsStream = AceHelper.class.getResourceAsStream(ace_js);
                InputStream ext_language_tools = AceHelper.class.getResourceAsStream(ext_language_tools_js);
//                InputStream themeJsStream = AceHelper.class.getResourceAsStream(theme_js);
        ) {
            StringBuilder html = new StringBuilder("""
                    <!DOCTYPE html>
                    <html lang="en">
                    <head>
                        <meta charset="UTF-8">
                        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
                        <title>AceDemo</title>
                        <style>
                            *{
                                padding:0px;
                                margin:0px;
                            }
                            html,body{
                                height: 100%;
                                width: 100%;
                                overflow: hidden;
                            }
                            #editor-container{
                                height: 100%;
                                width: 100%;
                                
                            }
                            .ace_editor.ace_autocomplete {
                                width: 415px;
                                z-index: 200000;
                                border: 1px lightgray solid;
                                position: fixed;
                                box-shadow: 2px 3px 5px rgb(0 0 0 / 20%);
                                line-height: 1.4;
                                background: #fefefe;
                                color: #111;
                            }
                        </style>
                    </head>
                    <body>
                    <div id="editor-container" ></div>

                    """);

            html.append("<script>").append(new String(Objects.requireNonNull(aceJsStream).readAllBytes(), StandardCharsets.UTF_8)).append("</script>\n").append("<!--要更改主题，只需包含主题的JavaScript文件-->\n").append("\n");

            //加载所有主题
            for (AceTheme value : AceTheme.values()) {
                String theme_path = "/static/editors/ace-builds/src-min/" + value.getName();
                InputStream themeStream = AceHelper.class.getResourceAsStream(theme_path);
                html.append("<script>").append(new String(Objects.requireNonNull(themeStream).readAllBytes(), StandardCharsets.UTF_8)).append("</script>\n");
            }

            for (AceMode value : AceMode.values()) {
                String model_js = "/static/editors/ace-builds/src-min/" + value.getName();
                InputStream modelJsStream = AceHelper.class.getResourceAsStream(model_js);
                html.append("<script>").append(new String(Objects.requireNonNull(modelJsStream).readAllBytes(), StandardCharsets.UTF_8)).append("</script>\n");
            }

            html.append("<script>").append(new String(Objects.requireNonNull(ext_language_tools).readAllBytes(), StandardCharsets.UTF_8)).append("</script>\n");

            html.append("""
                    <script>
                        var editor = ace.edit("editor-container");
                        // 使用主题:
                        editor.setTheme("ace/theme/xcode");
                        // 使用模式
                        editor.session.setMode("ace/mode/java");

                        //字体大小
                        editor.setFontSize(16);
                        //editor.setValue(Areacode);

                        //启动提示
                        var langTools = ace.require("ace/ext/language_tools");

                        editor.setOptions({
                            showGutter: true, // 显示左侧内容（行号和折叠内容）
                            lanuage: "java",
                            showFoldWidgets: true, // 显示折叠小部件
                            showLineNumbers: true, // 是否显示行号
                            readOnly: false, // 设置只读（true时只读，用于展示代码）
                            wrap: 'off', // 自动换行,off：关闭 , free：开启
                            enableBasicAutocompletion: true,
                            enableSnippets: true,
                            enableLiveAutocompletion: true,
                            showPrintMargin: false, // 打印边距
                        });

                        // 设置模式
                        function setEditorMode(mode){
                            editor.session.setMode(mode);
                        }

                        // 设置内容
                        function setEditorValue(value){
                            editor.setValue(value,1);
                            // editor.setValue("text2", -1); // set value and move cursor to the start of the text
                            // editor.session.setValue("the new text here"); // set value and reset undo history
                        }

                        // 获取内容
                        function getEditorValue(value){
                            return editor.getValue(); // or session.getValue
                        }

                        // 删除选中的内容
                        function removeSelectRange(){
                            var range = editor.getSelectionRange();
                            editor.remove(range);
                        }

                        // 监听窗口大小变化
                        window.addEventListener('resize', function() {
                            // 在这里执行窗口大小变化后的操作
                            editor.resize();
                        });

                        // 监听内容变化
                        editor.on('change', function(delta) {
                            // delta.start, delta.end, delta.lines, delta.action
                            try{
                                window.AceEditor.textChange(editor.getValue()); // 通知javafx(AceView)程序内容发生变化。
                            }catch(err){
                            }
                        });

                    </script>
                    </body>
                    </html>""");

            return html.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
